package demo.model.web;

import demo.model.domain.UserBean;
import demo.model.util.DBUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet(name = "LoginServlet2", value = "/LoginServlet2")
public class LoginServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Content-type", "text/html;charset=GBK");
        response.setCharacterEncoding("GBK");

        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        UserBean userBean = new UserBean();
        userBean.setName(name);
        userBean.setPassword(password);
        userBean.setEmail(email);

        boolean flag = DBUtil.getInstance().check(userBean);

        if (flag) {
            request.getSession().setAttribute("userBean", userBean);
            response.setHeader("refresh", "3;url=login.jsp");
        } else {
            request.setAttribute("DBMes", "用户名或密码错误！");
            request.getRequestDispatcher("/index_b.jsp")
                    .forward(request, response);
        }
        response.getWriter().print("恭喜你，登录成功！三秒后自动跳转");
        request.getSession().setAttribute("userBean", userBean);
        response.setHeader("refresh", "3,url=login.jsp");
    }
}
